package net.rlair.sbdemo.service;

import net.rlair.sbdemo.ContextUtils;
import net.rlair.sbdemo.dao.mybatis.bootmapper.UserMapper;
import net.rlair.sbdemo.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 事务测试
 */
@Component
public class TxNestedZhouLiangjun {

    @Resource
    private ContextUtils contextUtils;

    @Resource
    private UserMapper userMapper;

    @Transactional
    public Object batchSave() {
        final TxNestedZhouLiangjun tx = contextUtils.getApplicationContext().getBean(TxNestedZhouLiangjun.class);
        for (int i = 0; i < 5; i++) {
            final User user = new User();
            user.setName("name-" + i);
            user.setCreated(new Date());
            user.setPassword("pwd" + i);
            tx.insert(user);
        }
        return "ok";
    }

    @Transactional(propagation = Propagation.NESTED)
    public void insert(final User user) {
        if (("pwd4").equals(user.getPassword())) {
            //模拟运行时异常
            final int i = 1 / 0;
            System.out.println(i);
        }
        userMapper.addUser(user);
    }
}